package com.ybkj.daijia.server.websocket;

import com.ybkj.daijia.server.websocket.command.Command;
import com.ybkj.daijia.server.websocket.command.CommandFactory;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class TextMessageWebSocketHandler extends TextWebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(TextMessageWebSocketHandler.class);

    @Autowired
    private CommandFactory commandFactory;

    @Override
    protected void handleTextMessage(WebSocketSession session,
        TextMessage message) throws Exception {

        String payload = message.getPayload();
//		session.getHandshakeHeaders()
        logger.debug("payload:{}", payload);

        JSONObject json = new JSONObject(payload);
        String command = json.optString("command");

        Command cmd = commandFactory.getCommand(command);

        if (null != cmd) {

            cmd.handle(session, message);

        } else {
            logger.warn("No Processor Found For Command:{} Recv Message:{}", cmd, payload);
        }

    }


}
